import { useSearchIcon } from '@renderer/hooks'
import { useSettingStore, useSnippetsStore, useSuggestionStore } from '@renderer/stores'
import classNames from 'classnames'
import { useEffect } from 'react'
import styles from './styles.module.css'

export function Suggestion () {
  const systemSearchItems = useSettingStore(i => i.systemSearchItems)
  const browserSearchItems = useSettingStore(i => i.browserSearchItems)
  const activeSuggestionId = useSuggestionStore(s => s.activeSuggestionId)
  const setSearchValue = useSnippetsStore(state => state.setSearchValue)
  const setActiveSuggestionId = useSuggestionStore(s => s.setActiveSuggestionId)
  const { renerSearchIcon } = useSearchIcon(styles.suggestionIcon)

  useEffect(() => {
    const list = [
      ...systemSearchItems.filter(i => i.type !== 'snippets'),
      ...browserSearchItems,
    ]
    if (!list.length) {
      return
    }

    setActiveSuggestionId(list[0].id)
  }, [systemSearchItems, browserSearchItems])

  useEffect(() => {
    const list = [
      ...systemSearchItems.filter(i => i.type !== 'snippets'),
      ...browserSearchItems,
    ]

    const handler = (e: KeyboardEvent) => {
      if (e.code === 'Escape') {
        return window.api.closeWindow('search')
      }

      const maxIndex = list.length - 1
      if (e.code === 'ArrowDown') {
        setActiveSuggestionId((prevId) => {
          const index = list.findIndex(i => i.id === prevId)
          const nextIndex = index + 5
          if (nextIndex <= maxIndex) {
            return list[nextIndex].id
          }
          return prevId
        })
      } else if (e.code === 'ArrowUp') {
        setActiveSuggestionId((prevId) => {
          const index = list.findIndex(i => i.id === prevId)
          const nextIndex = index - 5
          if (nextIndex >= 0) {
            return list[nextIndex].id
          }
          return prevId
        })
      } else if (e.code === 'ArrowRight') {
        setActiveSuggestionId((prevId) => {
          const index = list.findIndex(i => i.id === prevId)
          const nextIndex = index + 1
          if (nextIndex <= maxIndex) {
            return list[nextIndex].id
          }
          return prevId
        })
      } else if (e.code === 'ArrowLeft') {
        setActiveSuggestionId((prevId) => {
          const index = list.findIndex(i => i.id === prevId)
          const nextIndex = index - 1
          if (nextIndex >= 0) {
            return list[nextIndex].id
          }
          return prevId
        })
      }
    }

    window.addEventListener('keydown', handler)

    return () => {
      window.removeEventListener('keydown', handler)
    }
  }, [
    systemSearchItems,
    browserSearchItems,
    systemSearchItems,
    browserSearchItems,
  ])

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (!activeSuggestionId) {
        return
      }

      const list = [
        ...systemSearchItems.filter(i => i.type !== 'snippets'),
        ...browserSearchItems,
      ]

      if (e.code === 'Enter') {
        const item = list.find(i => i.id === activeSuggestionId)
        if (!item) {
          return
        }

        setSearchValue(`${item.abbreviation} `)
      }
    }

    window.addEventListener('keydown', handler)

    return () => {
      window.removeEventListener('keydown', handler)
    }
  }, [activeSuggestionId, setSearchValue])

  return (
    <main className="bg-primary rounded-b-lg p-1 flex flex-wrap gap-2 text-white">
      {
        [
          ...systemSearchItems.filter(i => i.type !== 'snippets'),
          ...browserSearchItems,
        ].map(item => {
          return (
            <div
              key={item.id}
              className={classNames('flex flex-col items-center justify-center py-1 px-2 rounded-md cursor-pointer w-28 group', {
                ['bg-active']: activeSuggestionId === item.id,
              })}
              onClick={() => {
                setSearchValue(`${item.abbreviation} `)
              }}
            >
              { renerSearchIcon(item, item.name) }
              <span className='mt-1 group-hover:hidden'>{item.abbreviation}</span>
              <span className='mt-1 hidden group-hover:block'>{item.name}</span>
            </div>
          )
        })
      }
    </main>
  )
}
